DSWeb.Connect4 = function() {
	this.whichPlayer = 0;
	this.columns = [[],[],[],[],[],[],[]];
};

DSWeb.Connect4.prototype.init = function() {
	
	DSWeb.Connect4.instance = this;
	
	this.drawGrid();
	
	$('#Connect4Canvas').click(function(e) {
		DSWeb.Connect4.instance.boardClicked(e, $(this));
	});
	
	$('#Footer').hide();
};

DSWeb.Connect4.prototype.boardClicked = function(e, canvas) {
		
	var canvasX = e.pageX - canvas.offset().left;
	
	var column = Math.floor(canvasX / 50);
	var row = this.columns[column].length;
	
	if (row < 6) {
		
		this.drawPiece(column, row);
		this.columns[column].push(this.whichPlayer);
		
		if ( this.isGameOver() ) {
			
			
		} else {
			this.switchPlayerTurn();
		}
		
		console.log(this.columns);
	}
};

DSWeb.Connect4.prototype.isGameOver = function() {
	return false;
};

DSWeb.Connect4.prototype.switchPlayerTurn = function() {
	this.whichPlayer = 1 - this.whichPlayer;
	$('#WhoseTurn').removeClass(
		this.whichPlayer == 0 ? 'blue' : 'red'
	).addClass(
		this.whichPlayer == 0 ? 'red' : 'blue'
	).html(
		this.whichPlayer == 0 ? "Red's turn" : "Blue's turn"
	);
};

DSWeb.Connect4.prototype.getContext = function() {
	return document.getElementById('Connect4Canvas').getContext('2d');
};

DSWeb.Connect4.prototype.drawPiece = function(column, row) {
	var context = this.getContext();
	
	var x = 50.0 * column + 25.0;
	var y = 300 - 50 * row - 25.0;
	var radius = 23.0;
	
	context.fillStyle = (this.whichPlayer == 0) ? 'red' : 'blue';
	context.beginPath();
	context.arc(x, y, radius, 0, Math.PI * 2, true);
	context.closePath();
	context.fill();
};

DSWeb.Connect4.prototype.drawGrid = function() {
	var context = this.getContext();
	for (var x = 0; x <= 350; x += 50) {
		context.moveTo(x, 0);
		context.lineTo(x, 300);
	}
	for (var y = 0; y <= 300; y += 50) {
		context.moveTo(0, y);
		context.lineTo(350, y);
	}
	context.stroke();
};